<template>
  <div class="container">
    <div class="header">
      <!-- <h3 class="myday" ref='myday' @blur="alterTitle" @keyup.enter='stopEnter'>{{check.title}}</h3> -->
      <input ref='title' type="text" :value="check.title" @focus="selection" @blur="alterTitle" @keyup.enter='stopEnter'>
    </div>
    <div class="todo">
      <ul>
        <li
          is="todo"
          v-for="todo in check.tasks"
          v-bind:key="todo.index"
          v-bind:index="todo.index"
          v-bind:isDone="todo.isDone"
          v-bind:title="todo.todo"
        ></li>
      </ul>
      <div class="newtodo">
        <i class="el-icon-plus" v-show='!circleVisible' @click='getfocus'></i>
        <svg class="icon circle" v-show="circleVisible" aria-hidden="true">
            <use xlink:href="#icon-uncheck"></use>
        </svg>
        <input ref='inputfocus' type="text" v-model="todoVal" placeholder="添加待办事项" @blur="losefocus" @focus="circleVisible = true" @keyup.enter="addTodo">
      </div>
      <div class="temptodo"></div>
    </div>
  </div>
</template>

<script>
import todo from "@/components/todo";
import { mapState, mapGetters } from "vuex";
export default {
  name: "todolist",
  data() {
    return {
      circleVisible: false,
      todoVal: "",
      newTodoId: 0
    };
  },
  components: { todo },
  methods: {
    // 点击+获得焦点并改变icon显示
    getfocus() {
      this.circleVisible = !this.circleVisible;
      this.$refs.inputfocus.focus();
    },
    // 失去焦点，改变icon显示
    losefocus() {
      this.circleVisible = false;
    },
    // 新增待办事项
    addTodo() {
      this.todos.push({
        id: this.newTodoId++,
        title: this.todoVal
      });
      this.todoVal = "";
    },
    // 获取焦点时，全选内容
    selection() {
      this.$refs.title.select();
    },
    // 失去焦点，修改title
    alterTitle(e) {
      let title = e.target.value
      let id = this.$route.params.id
      let list = this.$store.state.checklist.checkList
      this.$store.dispatch({
        type: 'alterCheckTitle',
        title
      }).then(res => {
        // 动态更改代办清单上的title
        list.map((v,i) => {
          if(v.id === id) {
            v.title = title
          }
        })
      }).catch((error) => {
        console.log(error)
      })
    },
    // 阻止回车
    stopEnter(e) {
      this.$refs.title.blur()
    }
  },
  computed: {
    ...mapGetters(['check'])
  },
  beforeRouteEnter(to, from, next) {
    const id = to.params.id;
    next(vm => {
      vm.$store.commit({
        type: "getCheckid",
        id
      });
    });
  },
  beforeRouteUpdate(to, from, next) {
    const id = to.params.id;
    this.$store.commit({
      type: "getCheckid",
      id
    });
    next();
  }
};
</script>

<style scoped lang="less" src="./index.less"></style>

